package tgc.edu.examxy.web.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import net.sf.json.JSONObject;
import tgc.edu.examxy.custom.AjaxResult;
import tgc.edu.examxy.custom.HtmlTurnWx;
import tgc.edu.examxy.custom.TimeUtils;
import tgc.edu.examxy.custom.dict.entity.SystemData;
import tgc.edu.examxy.custom.dict.entity.TbClassType;
import tgc.edu.examxy.custom.dict.service.SystemDataService;
import tgc.edu.examxy.custom.dict.service.TbClassTypeService;
import tgc.edu.examxy.entity.ArticleManagement;
import tgc.edu.examxy.entity.AskForleave;
import tgc.edu.examxy.entity.Checkingin;
import tgc.edu.examxy.entity.CurriculumPlan;
import tgc.edu.examxy.entity.Evaluation;
import tgc.edu.examxy.entity.EvaluationRule;
import tgc.edu.examxy.entity.EvaluationXz;
import tgc.edu.examxy.entity.Student;
import tgc.edu.examxy.entity.StudentInformation;
import tgc.edu.examxy.entity.SysUser;
import tgc.edu.examxy.entity.TbClass;
import tgc.edu.examxy.security.User2;
import tgc.edu.examxy.service.ArticleManagementService;
import tgc.edu.examxy.service.AskForleaveService;
import tgc.edu.examxy.service.CheckinginService;
import tgc.edu.examxy.service.CurriculumPlanService;
import tgc.edu.examxy.service.EvaluationRuleService;
import tgc.edu.examxy.service.EvaluationService;
import tgc.edu.examxy.service.EvaluationXzService;
import tgc.edu.examxy.service.StudentInformationService;
import tgc.edu.examxy.service.StudentService;
import tgc.edu.examxy.service.SysFileService;
import tgc.edu.examxy.service.SysUserService;
import tgc.edu.examxy.service.TbClassService;
import tgc.edu.examxy.web.form.AndroidArticleForm;
import tgc.edu.examxy.web.form.AndroidCjForm;
import tgc.edu.examxy.web.form.AndroidClassTypeFrom;
import tgc.edu.examxy.web.form.AndroidEvationRuleForm;
import tgc.edu.examxy.web.form.AndroidKbForm;
import tgc.edu.examxy.web.form.AndroidgoArticleForm;
import tgc.edu.examxy.web.form.ClasstypeForm;
import tgc.edu.examxy.web.form.RegisterForm;
import tgc.edu.examxy.web.form.RegisterForm2;
import tgc.edu.examxy.web.form.RegisterForm3;
@Controller
@RequestMapping(value = "/android")
public class AndroidController {
	@Autowired
	private SysUserService userService;
	@Autowired
	private CurriculumPlanService curriculumervice;
	@Autowired
	private StudentService studentservice;
	@Autowired
	private CheckinginService CheckinginService ;
	@Autowired
	private StudentInformationService inService;
	@Autowired
	private CheckinginService  checkinginservice;
	@Autowired
	private EvaluationRuleService erservice;
	@Autowired
	private EvaluationXzService exService;
	@Autowired
	private EvaluationService Evaluationservice;
	@Autowired
	private AskForleaveService askservice;
	@Autowired
	private SysFileService fileservice;
	@Autowired//数据字典连接类
	private SystemDataService systemdataservice;
	@Autowired
	private TbClassTypeService typeservice;
	@Autowired
	private TbClassService tbClassService;
	@Autowired
	private SysUserService userservice;
	/***
	 * 获取课表
	 * @param username
	 * @return
	 */
	@RequestMapping(value = "/tocurriculum")
	@ResponseBody
	private Object toCurriculum(String openid) {
		Student usernames = studentservice.findByOpenid(openid,"已通过");
		if(usernames!=null) {
			//取出所有课程信息
			Sort sort=Sort.by("starttime");
			Specification<CurriculumPlan> spec = buildSpeccurriculum(usernames);
			List<CurriculumPlan> clist = curriculumervice.findAll(spec, sort);
			//取出需要的的字段存入androidkb
			List<AndroidKbForm> androidkb = new ArrayList<>();
			for (CurriculumPlan c : clist) {
				AndroidKbForm form = new AndroidKbForm();
				form.setStarttime(c.getStarttime());
				form.setFinishttime(c.getFinishttime());
				form.setTeacher(c.getTeacher().getName());
				form.setKc(c.getCurriculum().getCourseName());
				form.setStudentid(usernames.getId());
				form.setCurriculumPlanid(c.getId());
				//查看当前课程签到情况，和是否需要签到状态
				
				Checkingin findByQd = CheckinginService.findByCurriculumPlanAndStudentAndBjuuid(c.getId(), usernames,usernames.getTbClass().getId().toString());
				
				if(findByQd==null) {
					form.setQd(curriculumervice.getQd(c.getStarttime()));
				}else {
					String isReach = findByQd.getIsReach();
					if(isReach==null||isReach=="") {
						form.setQd(curriculumervice.getQd(c.getStarttime()));;
					}else {
						form.setQd(3);
					}
					
				}
				androidkb.add(form);
			}
			
			return androidkb;
		}
		return new AjaxResult(false, "不存在此用户，或未通过注册！");
	}

	
	/****
	 * 根据接收的openid判断用户表中是否有该openid对应的用户，有则返回true，否则返回false
	 * @return
	 */
	@RequestMapping(value = "/toOpenid")
	@ResponseBody
	private AjaxResult toOpenid(String openid) {
		SysUser user = userService.findByOpenid(openid);
		if(user!=null) {
			Student student = studentservice.findByTypeAndOpenid("已通过",openid);
			if(student!=null){
				return new AjaxResult(true, "存在");				
			}
			return new AjaxResult(false,"不存在");//这里会有一种状态1.用户注册待审核的！
		}else {
			return new AjaxResult(false,"不存在");//这里两种状态：1.用户没有注册！2.用户没有绑定微信小程序！
		}
	}
	
	/****
	 *  注册功能 改名----用户状态查询 需要注册，还是需要绑定
	 * 根据openid和身份证号进行注册，如果身份证号在用户表中存在，将openid写入对应用户信息返回注册成功
	 * 若不存在，返回“身份证号不存在，注册失败”；
	 * @param openid	微信唯一标识
	 * @param username 身份证号
	 * @return
	 * 1 ---- 需要注册
	 * 2 ---- 用户需要等待管理员审核
	 * 
	 * 3 ---- 用户已是正常用户，提醒用户重新登入小程序（基本不会出现）
	 * 4 ---- 用户提供的身份证号和小程序绑定的用户不一样，通知管理员进行处理，或者提醒用户输入的合法性（可能用互结业时，管理端未进行处理。这里抛出异常）
	 */
	@RequestMapping(value = "/toUser")
	@ResponseBody
	private AjaxResult toUser(String openid,String username) {
		SysUser user = userService.findByUsername(username);
		if(user==null) {
			return new AjaxResult(false, "1");//用户需要注册
		}
		SysUser openids = userService.findByOpenid(openid);
		if(openids==null) {
			Student student = studentservice.findByTypeAndUsername("已通过",username);
			//当用户已注册，且openid为空，用户不为空时，用户即进行绑定
			if(student!=null) {
				user.setOpenid(openid);
				userService.save(user);
				return new AjaxResult("成功绑定用户！");
			}else {
				return new AjaxResult(false,"2");//用户需要等待管理审核
			}
		}
		//以下情况基本不会出现，除非在网卡时toOpenid出现错误时出现情况
		if(user.getId()==openids.getId()) {
			return new AjaxResult(false,"3");//用户已是正常用户，提醒用户重新登入小程序
		}else {
			return new AjaxResult(false,"4");//用户提供的身份证号和小程序绑定的用户不一样，通知管理员进行处理
		}
	}
	
	
	/****
	 * 获取我的成绩
	 * @param username
	 * @return
	 */
	@RequestMapping(value = "/toMyperformance")
	@ResponseBody
	private Object toMyperformance(String openid) {
		Student student = studentservice.findByTypeAndOpenid("已通过",openid);
		if(student==null){
			return new AjaxResult(false, "不存在此用户，或未通过注册！");				
		}
		
		List<StudentInformation> toMyperformance = inService.findByAssessStudentOpenid(openid);
		List<AndroidCjForm> androidlist = new ArrayList<>();
		for (StudentInformation a : toMyperformance) {
			AndroidCjForm form = new AndroidCjForm();
			form.setExamination(a.getInformation().getExamination());
			form.setScoringmethod(a.getInformation().getScoringmethod());
			form.setExplain(a.getInformation().getExplain());
			form.setScore(a.getInformation().getScore());
			form.setGrade(a.getGrade());
			androidlist.add(form);
		}
		return androidlist;
	}
	
	/****
	 * 	签到，根据接收的两个字符串（格式如“05月14日10:00~11:30”,串中符号为英文符号）的一致性判断是否正常签到
	 * 	正常则记录该学员该次课的考勤
	 * @return
	 */
	@RequestMapping(value = "/goSignIn")
	@ResponseBody
	private AjaxResult goSignIn(String openid,String curriculumPlanid,String curriculumPlan) {
		Student student = studentservice.findByTypeAndOpenid("已通过",openid);
		if(student==null){
			return new AjaxResult(false, "签到失败");		
		}
		try {
			if(curriculumPlan.equals(curriculumPlanid)) {
				//获取当前时间
				SimpleDateFormat dateFormat2= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
				SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd"); 
				String currenttime2 = dateFormat2.format(new Date());
				String currenttime = dateFormat.format(new Date()); 
				
				//保存到数据库
				Student students = studentservice.findByOpenid(openid);
				CurriculumPlan currplan = curriculumervice.findById(UUID.fromString(curriculumPlanid));
				
				Checkingin che = checkinginservice.findByCurriculumPlanAndStudentAndBjuuid(UUID.fromString(curriculumPlanid),students,students.getTbClass().getId().toString());
				if(che!=null) {
					//如果这个学员存在，则新增一条数据
					che.setIsReach("正常");
					che.setTime(currenttime2);
					checkinginservice.save(che);
				}else {
					//这个防止如果在期间突然换学员导致没有记录，然后签到自动添加一条记录
					Checkingin checkingin = new Checkingin();
					checkingin.setCurriculumPlan(UUID.fromString(curriculumPlanid));
					checkingin.setCurriculumName(currplan.getCurriculum().getCourseName());
					checkingin.setTime(currenttime2);
					checkingin.setBjuuid(students.getTbClass().getId().toString());
					checkingin.setBanji(students.getTbClass().getName());
					checkingin.setStudent(students);
					checkingin.setIsReach("正常");
					checkingin.setDates(currenttime);
					checkinginservice.save(checkingin);
				}
				return new AjaxResult(true, "签到成功");
			}
		} catch (Exception e) {
			return new AjaxResult(false, "签到失败");
		}
		return new AjaxResult(false, "签到失败");
		
	}
	
	
	
	/****
	 * 安全查询，获取课表
	 * @param username
	 * @return
	 */
	private Specification<CurriculumPlan> buildSpeccurriculum(Student usernames) {
		
		Specification<CurriculumPlan> specification = new Specification<CurriculumPlan>() {
			private static final long serialVersionUID = 1L;
			@Override
			public Predicate toPredicate(Root<CurriculumPlan> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				if(usernames!=null) {
					Predicate name = cb.equal(root.get("tbClass").get("id"), usernames.getTbClass().getId());
					rules.add(name);
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return specification;
	}
	
	@RequestMapping("/getWxUserInfo")
	@ResponseBody
	public JSONObject getSessionKeyOropenid(String appid,String secret,String code,String granttype){
		Map<String,String> requestUrlParam = new HashMap<String,String>();
		requestUrlParam.put("appid", appid);
		requestUrlParam.put("secret", secret);
		requestUrlParam.put("js_code", code); 
		requestUrlParam.put("grant_type", granttype);
		JSONObject jsonObject = JSONObject.fromObject(sendPost("https://api.weixin.qq.com/sns/jscode2session", requestUrlParam));  
		return jsonObject;	
		//return sendPost("https://api.weixin.qq.com/sns/jscode2session", requestUrlParam);
	}

	
	/**
	* 向指定 URL 发送POST方法的请求
	* 
	* @param url
	*            发送请求的 URL
	* @param param
	*            请求参数
	* @return 所代表远程资源的响应结果
	*/
	public String sendPost(String url, Map<String, ?> paramMap) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";

		String param = "";
		Iterator<String> it = paramMap.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next();
			param += key + "=" + paramMap.get(key) + "&";
		}
		param = param.substring(0, param.length() - 1);
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Accept-Charset", "utf-8");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {

		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
	/***
	 * 获取用户的JSON数据
	 * @param openid
	 * @return
	 */
	@RequestMapping(value = "/getUser")
	@ResponseBody
	private Object getUser(String openid) {
		Student student  = studentservice.findByOpenid(openid);
		if(student!=null) {
			return student;
		}
		return new AjaxResult(false, "此用户不存在");
	}
	
	/****
	 * 1.同学录 --- 班级信息
	 * 获取同班同学的信息，相当于
	 * 需要传过来用户的openid
	 * @param openid
	 * @return
	 */
	@RequestMapping(value="/totbClass")
	@ResponseBody
	private Object totbClass(String openid) {
		Student student  = studentservice.findByOpenid(openid);
		if(student==null) {
			return new AjaxResult(false, "此用户不存在");
		}
		List<Student> students = studentservice.findByTbClassAndTypeAndIsUsed(student.getTbClass(),"已通过",true);
		if(students.size()<1) {
			return new AjaxResult(false, "这个班的学员为空");
		}
		return students;
	}
		
	//***** 课程评价  *****//
	/****
	 * 首先获取需要评价的课程
	 * @return
	 */
	@RequestMapping(value="/tocourseEvaluation")
	@ResponseBody
	private Object getEvaluation(String openid) {
		Student student  = studentservice.findByOpenid(openid);
		if(student==null) {
			return new AjaxResult(false, "此用户不存在");
		}
		if(student.getUsername()==null) {
			return new AjaxResult(false, "此用户没有用户名！");
		}
		// 根据班级 查找出所有	生成这个学生需要评价的信息
		List<CurriculumPlan> teachings = curriculumervice.findByTbClass(student.getTbClass());
		int rulesort = 2;
		for (CurriculumPlan t : teachings) {
			EvaluationRule ers = erservice.findByStudentIdAndTeachingProgrammeId(student.getId(), t.getId());
			if (ers == null && student.getId() != null && t.getId() != null) {
				EvaluationRule erentity = new EvaluationRule();
				erentity.setStudentId(student.getId());
				erentity.setTeachingProgrammeId(t.getId());
				erentity.setTbClassId(t.getTbClass().getId());
				erentity.setTeacherId(t.getTeacher().getId());
				erentity.setStudentname(student.getName());
				erentity.setStudentusername(student.getUsername());
				erentity.setTbClassName(t.getTbClass().getName());
				erentity.setTbClassTeachername(t.getTbClass().getTeacherId().getName());
				erentity.setTbCurriculumCourseName(t.getCurriculum().getCourseName());
				erentity.setTeacherName(t.getTeacher().getName());
				erentity.setIsUsed(true);
				erentity.setTime(t.getFinishttime());
				/** 查看状态 **/
				Integer comparisontime = TimeUtils.Comparisontime(t.getFinishttime());
				erentity.setIsevaluate(comparisontime);
				
				int rulesort2 = TimeUtils.rulesort(t.getFinishttime(),rulesort);
				erentity.setRulesort(rulesort2);
				erentity.setTeachingProgrammeType("TYPE_ONE");
				erservice.save(erentity);
			}else {
				//改变状态
				if(ers.getIsevaluate()!=2) {
					Integer comparisontime = TimeUtils.Comparisontime(t.getFinishttime());
					ers.setIsevaluate(comparisontime);
					int rulesort2 = TimeUtils.rulesort(t.getFinishttime(),rulesort);
					ers.setRulesort(rulesort2);
					erservice.save(ers);
				}
			}
		}
		Sort sort = Sort.by("rulesort");
		List<EvaluationRule> list = erservice.findByStudentId(student.getId(),sort);
		if(list.size()<1) {
			return new AjaxResult(false, "无课程需要评价");
		}
		List<AndroidEvationRuleForm> forms = new ArrayList<>();
		/** 将需要的参数传递到前台 **/
		for (EvaluationRule evaluationRule : list) {
			AndroidEvationRuleForm form = new AndroidEvationRuleForm();
			form.setId(evaluationRule.getId());
			form.setTbCurriculumCourseName(evaluationRule.getTbCurriculumCourseName());
			form.setTeacherName(evaluationRule.getTeacherName());
			/** 数据转换 **/
			Integer is = evaluationRule.getIsevaluate();
			if(is==2) {
				form.setIsevaluate(evaluationRule.getGrads().toString());
			}else if(is==1){
				form.setIsevaluate("未评价");
			}else if(is==3) {
				form.setIsevaluate("待评价");
			}else if(is==4) {
				form.setIsevaluate("已过期");
			}
			forms.add(form);
		}
		return forms;
	}
	
	/****
	 * 当用户点击评论时
	 * 需要把几个需要评论的体系进行保存和传到前台
	 * 相当于前台需要评价的那几个点
	 * @return
	 *//*
	@RequestMapping(value="/toEvaluation")
	@ResponseBody
	private Object toEvaluation(String uuid) {
		EvaluationRule rules = erservice.findById(UUID.fromString(uuid));
		if (rules != null) {
			List<EvaluationXz> xzentity = exService.findByType(rules.getTeachingProgrammeType());
			for (EvaluationXz exz : xzentity) {
				Evaluation evaluations = Evaluationservice.findByEvaluationRuleAndEvaluationXzId(rules, exz.getId());
				if (evaluations == null) {
					Evaluation Evaluationentitys = new Evaluation();
					Evaluationentitys.setEvaluationRule(rules);
					Evaluationentitys.setEvaluationXzId(exz.getId());
					Evaluationentitys.setType(exz.getType());
					Evaluationentitys.setExplain(exz.getExplain());
					Evaluationentitys.setSystem(exz.getSystem());
					Evaluationentitys.setWeight(exz.getWeight());
					Evaluationservice.save(Evaluationentitys);
				}
			}
			List<Evaluation> list  = Evaluationservice.findByEvaluationRule(rules);
			return list;
		}else {
			return new AjaxResult(false, "此课程不存在");
		}
	}*/
	/****
	 * 保存评价的方法
	 * uuid 评价的课程ID
	 * evaluation 课程点评
	 * grade 打的星级  最好是数字 1，2，3，4，5
	 * 还有打分，如果时多个， 看是以 数组传过来，还是JSON传到后台来
	 * @return
	 */
	@RequestMapping(value= "/evaluationsave")
	@ResponseBody
	private Object goEvaluationsave(String uuid,String evaluation,String grade) {
		try {
			EvaluationRule rules = erservice.findById(UUID.fromString(uuid));
			if(rules==null) {
				return new AjaxResult(false, "评价课程不存在，无法评价");
			}
			List<EvaluationXz> xzentity = exService.findByType(rules.getTeachingProgrammeType());
			for (EvaluationXz exz : xzentity) {
				Evaluation evaluations = Evaluationservice.findByEvaluationRuleAndEvaluationXzId(rules, exz.getId());
				if (evaluations == null) {
					Evaluation Evaluationentitys = new Evaluation();
					Evaluationentitys.setEvaluationRule(rules);
					Evaluationentitys.setEvaluationXzId(exz.getId());
					Evaluationentitys.setType(exz.getType());
					Evaluationentitys.setExplain(exz.getExplain());
					Evaluationentitys.setSystem(exz.getSystem());
					double weight = exz.getWeight();
					Evaluationentitys.setWeight(weight);
					double d= 0.0;
					try {
						d = Double.valueOf(grade);
					} catch (Exception e) {
						d= 0.0;
					}
					rules.setGrads(d);
					Evaluationentitys.setPostgrade(d);
					Evaluationentitys.setGrade(d);
					Evaluationentitys.setPostisno("微信小程序上评价的！");
					Evaluationservice.save(Evaluationentitys);
				}
			}
			rules.setRulesort(4000);
			rules.setIsevaluate(2);
			rules.setEvaluation(evaluation);
			erservice.save(rules);
			return new AjaxResult(true, "保存成功！");
		} catch (Exception e) {
			return new AjaxResult(false, "数据保存失败！");
		}
		
	}
	/******** 请假 ********/
	/***
	 * 获取所有请假记录
	 * @param openid 学员ID
	 * @return
	 */
	@RequestMapping(value= "/getforleave")
	@ResponseBody
	private Object getForleave(String openid) {
		Student student  = studentservice.findByOpenid(openid);
		if(student==null) {
			return new AjaxResult(false, "此用户不存在");
		}
		Sort sort = Sort.by("startDate");
		List<AskForleave> ask =askservice.findByStudentId(student.getId(),sort);
		for (AskForleave askForleave : ask) {
			askForleave.setStartDate(askForleave.getStartDate().substring(0, askForleave.getStartDate().length()-3));
			askForleave.setEndDate(askForleave.getEndDate().substring(0, askForleave.getEndDate().length()-3));
		}
		if(ask.size()<1) {
			return new AjaxResult(false, "无请假记录");
		}
		return ask;
	}
	
	/****
	 * 保存请假记录
	 * 1.openid 请假学生的ID
	 * @param startDate 请假开始时间
	 * @param endDate	请假结束时间
	 * @param reasonforleave	请假原因
	 * @param file	图片
	 * @return
	 */
	@RequestMapping(value= "/saveForleave")
	@ResponseBody
	private Object saveForleave(String openid,String startDate,String endDate,String reasonforleave,MultipartFile file) {
		Student student  = studentservice.findByOpenid(openid);
		if(student==null) {
			return new AjaxResult(false, "此用户不存在");
		}
		String uuid = UUID.randomUUID().toString();
		AskForleave ask = new AskForleave(); 
		ask.setStudentId(student.getId());
		ask.setStuName(student.getName());
		ask.setTbClass(student.getTbClass().getName());
		startDate = startDate + ":00";
		ask.setStartDate(startDate);
		endDate = endDate + ":00";
		ask.setEndDate(endDate);
		ask.setReasonforleave(reasonforleave);
		ask.setLeavefile(uuid);
		ask.setState(1);
		try {
			fileservice.savefile(file, uuid);
			askservice.save(ask);
			return new AjaxResult(true, "请假成功");
		} catch (Exception e) {
			return new AjaxResult(false, "数据保存失败");
		}
		
	}
	
	
	
	
	/**** 公告 *****/
	@Autowired
	private ArticleManagementService articleservice;
	
	/****
	 * 获取标题
	 * @return
	 */
	@RequestMapping(value="toArticle")
	@ResponseBody
	private Object toArticleManagement() {
		Sort sort = Sort.by("updateDate");
		List<AndroidArticleForm> article = articleservice.findByType("微信",sort);
		return article;
	}
	/****
	 * 获取内容
	 * @param id
	 * @return
	 */
	@RequestMapping(value="goArticle")
	private String goArticleManagement(String id,ModelMap map) {
		ArticleManagement manage = articleservice.findById(UUID.fromString(id));
		map.put("manage", manage);
		return "android/goArticle";
	}
	/***
	 * 获取内容
	 * 只获取数据
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/goArticleManagement")
	@ResponseBody
	private Object goArticleManagement(String id) {
		ArticleManagement manage = articleservice.findById(UUID.fromString(id));
		String htmltruewx = HtmlTurnWx.htmltruewx(manage.getContent());
		manage.setContent(htmltruewx);
		return manage;
	}
	/**<----- 用户注册功能 ------->**/
	
	/****
	 * 获取字典的动态数据
	 * @param code 传值获取数据对象
	 * 1.性别：sex	2.民族：nation	3.政治面貌：political_outlook 4.学历：education
	 * 5.是否库区移民：isimmigrant
	 * 
	 * form提交的表单中select的value的内容建议还是用 参数.name
	 * 数据库保存的数据都不是代码code参数,因为后期数据转换的问题，所以存的都是名称
	 * @return
	 */
	@RequestMapping(value="toSystemData")
	@ResponseBody
	private Object SystemData(String code) {
		Order order=new Order(Direction.fromString("ASC"), "createDate");
		Sort sort=Sort.by(order);
		List<SystemData> findBySystemDictionariesCode = systemdataservice.findBySystemDictionariesCode(code,sort);
		//HashMap<String, List<String>>  hash = new HashMap<>();
		List<String> list = new ArrayList<>();
		for (SystemData systemData : findBySystemDictionariesCode) {
			list.add(systemData.getName());
		}
		//hash.put("name",list);
		return list;
	}
	
	/***
	 * 获取动态的班级
	 * 主题班
	 * 专题班
	 * 
	 * @return
	 */
	@RequestMapping(value = "/toclasstype")
	@ResponseBody
	public Object goXybm() {
		List<AndroidClassTypeFrom> androidClass= new ArrayList<>();
		List<TbClassType> type = typeservice.findAll();
		for (TbClassType tbClassType : type) {
			AndroidClassTypeFrom form =new AndroidClassTypeFrom();
			form.setId(tbClassType.getId());
			form.setName(tbClassType.getType());
			List<TbClass> tbclasslist = tbClassService.findByTbClassId(tbClassType.getId());
			List<RegisterForm3> tb = new ArrayList<>();
			for (TbClass tbClass : tbclasslist) {
				boolean ifTime = tbClassService.ifTime(tbClass);// 判断当前的时间
				if (ifTime) {
					RegisterForm3 res = new RegisterForm3();
					res.setId(tbClass.getId());
					res.setName(tbClass.getName());
					res.setStartTime(tbClass.getStartTime());
					res.setCloseTime(tbClass.getCloseTime());
					tb.add(res);
				}
			}
			form.setRegister(tb);
			androidClass.add(form);
		}
		return androidClass;
	}
	
	/***
	 * 获取对应主体班的  班级
	 * 其中加了开班时间等校验
	 * @param value
	 * @return
	 */
	/*@RequestMapping(value = "/gotbClass")
	@ResponseBody
	private Object tbClass(String uuid) {
		if(uuid==null||uuid=="") {
			return null;
		}
		List<TbClass> tbclasslist = tbClassService.findByTbClassId(UUID.fromString(uuid));
		List<RegisterForm3> tb = new ArrayList<>();
		for (TbClass tbClass : tbclasslist) {
			boolean ifTime = tbClassService.ifTime(tbClass);// 判断当前的时间
			if (ifTime) {
				RegisterForm3 res = new RegisterForm3();
				res.setId(tbClass.getId());
				res.setName(tbClass.getName());
				res.setStartTime(tbClass.getStartTime());
				res.setCloseTime(tbClass.getCloseTime());
				tb.add(res);
			}
		}
		return tb;
	}*/
	
	/***
	 * 学员注册 账号为身份证号码 密码为身份证后6位
	 * 
	 * @param form
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/toXybmsave")
	@ResponseBody
	public Object toXybmsave(RegisterForm form, ModelMap map,MultipartFile file) {
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		String uuid = UUID.randomUUID().toString();
		try {
			fileservice.savefile(file, uuid);
		} catch (Exception e) {
			uuid = null;
		}
		form.setFileuuid(uuid);
		if(form.getIdcode()==null||form.getIdcode()=="") {
			return new AjaxResult(false,"身份证号不能为空");
		}
		SysUser ifusernull = userservice.findByUsername(form.getIdcode());
		if (ifusernull == null && form.getName() != null && form.getIdcode() != null) {
			Student studententity = new Student();
			String pwd = form.getIdcode();
			String password = pwd.substring(pwd.length() - 6, pwd.length());
			studententity.setUsername(form.getIdcode());
			studententity.setPassword(encoder.encode(password));
			studententity.setGroup1(false);
			studententity.setType("待审核");
			TbClass tbclassEntity = tbClassService.findById(UUID.fromString(form.getTbClassNmae()));
			
			String maxStudent = studentservice.maxStudent(tbclassEntity);
			String serical = tbClassService.serical(tbclassEntity,maxStudent);
			studententity.setSerial(serical);
			
			studententity.setTbClass(tbclassEntity);
			BeanUtils.copyProperties(form, studententity, "id");
			studentservice.saves(studententity);
			fileservice.DeleteAll(form.getFileuuid());
			map.put("username", form.getIdcode());
			map.put("password", password);
			return new AjaxResult("注册成功");
		} else {
			Student students = studentservice.findById(ifusernull.getId());
			if(students.getType().equals("已拒绝")||students.getType().equals("")) {
				students.setName(form.getName());
				students.setSex(form.getSex());
				students.setNation(form.getNation());
				students.setBron(form.getBron());
				students.setPolitics(form.getPolitics());
				students.setDegree(form.getDegree());
				students.setSpeciality(form.getSpeciality());
				students.setWorkUnit(form.getWorkUnit());
				students.setJob(form.getJob());
				students.setJobLevel(form.getJobLevel());
				students.setOfficetel(form.getOfficetel());
				students.setPhone(form.getPhone());
				students.setAddress(form.getAddress());
				students.setPostalCode(form.getPostalCode());
				students.setIsimmigrant(form.getIsimmigrant());
				students.setFileuuid(form.getFileuuid());
				
				if(students.getType().equals("已通过")) {
					//保存原来班级的ID
					students.setTbClassid(students.getTbClass().getId());
				}
				//将用户状态改为待审核
				students.setType("待审核");
				//清空这个用户的权限
				students.setRoles(null);
				students.setGroup1(false);
				//保存新选择的班级
				TbClass tbclassEntity = tbClassService.findById(UUID.fromString(form.getTbClassNmae()));
				
				String maxStudent = studentservice.maxStudent(tbclassEntity);
				String serical = tbClassService.serical(tbclassEntity,maxStudent);
				students.setSerial(serical);
				students.setTbClass(tbclassEntity);
				studentservice.save(students);
				map.put("username", form.getIdcode());
				return new AjaxResult("注册成功");
			}else {
				return new AjaxResult(false, "身份证号已存在，请勿重复注册！");//当用户已存在，则不能进行二次注册！
			}
			
		}
	}

	/******* 
	 * 	获取学院证书ID
	 * 
	 *  下载证书地址
	 *  http://localhost/jeecgxy/download?uuid=ede121b6-6029-4a2f-bd9a-cf87ff7eaa8f
	 * 
	 * @return 
	 * ******/
	@RequestMapping(value="/toCertificate")
	@ResponseBody
	private HashMap<String, String> toCertificate(String openid) {
		Student findByOpenid = studentservice.findByOpenid(openid);
		String certificateuuid = findByOpenid.getCertificateuuid();
		HashMap<String, String> hash = new HashMap<>();
		hash.put("uuid",certificateuuid);
		return hash;
	}
	
}
